/**
 * @(#)JDOImageStorage.java, 2010-5-22. 
 * 
 */
package com.rsstuan.storage.impl;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.rsstuan.storage.data.ImageData;

/**
 *
 * @author guosq
 *
 */
public class JDOImageStorage {

    public void saveImage(Long itemId, byte[] data) {
        ImageData image = new ImageData();
        Key key = KeyFactory.createKey(ImageData.class.getSimpleName(), itemId);
        Blob blob = new Blob(data);
        image.setKey(key);
        image.setData(blob);
        
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            pm.makePersistent(image);
        }
        finally {
            pm.close();
        }
    }
    
    public byte[] getImage(Key key) {
        PersistenceManager pm = PMF.get().getPersistenceManager(); 
        try {
            ImageData image = (ImageData)pm.getObjectById(ImageData.class, key);
            if (image != null && image.getData() != null)
                return image.getData().getBytes().clone();
            return null;
        }
        catch (Exception e) {
        	return null;
        }
        finally {
            pm.close();
        }
    }
    
    public byte[] getImage(Long itemId) {
        Key key = KeyFactory.createKey(ImageData.class.getSimpleName(), itemId);
        return getImage(key);
    }
}
